import http from '@ohos.net.http'

// 响应内容中的 content item 类型
interface MessageContentText {
  text: string;
  type: 'text';
}

// usage 字段
interface MessageUsage {
  input_tokens: number;
  output_tokens: number;
}

// 主消息结构（与之前一致）
interface AssistantMessage {
  content: MessageContentText[];
  id: string;
  model: string;
  role: 'assistant';
  stop_reason: 'end_turn';
  stop_sequence: null;
  type: 'message';
  usage: MessageUsage;
}

// 性能时序（单位：毫秒）
interface PerformanceTiming {
  dnsTiming: number;
  tcpTiming: number;
  tlsTiming: number;
  firstSendTiming: number;
  redirectTiming: number;
  firstReceiveTiming: number;
  responseHeaderTiming: number;
  responseBodyTiming: number;
  totalFinishTiming: number;
  totalTiming: number;
}

// 响应头
interface ResponseHeader {
  connection: string;
  'content-length': string;
  'content-type': string;
  date: string;
}

// 主响应类型
interface ApiResponse {
  responseCode: number;
  cookies: string;
  header: ResponseHeader;
  result: string; // 注意：这是 JSON 字符串，不是对象
  resultType: 0; // 目前是字面量 0，可能是枚举
  performanceTiming: PerformanceTiming;
}

export async function askSiliconAI(question: string): Promise<string> {
  // ========= 初始化
  const url = 'https://api.siliconflow.cn/v1/messages';
  const token = 'sk-aynfjnjovbegojjtubqcvcoaslkboimdsfifrvleiymfpojv';
  const httpRequest = http.createHttp();

  // ========= 参数
  const body = {
    model: "deepseek-ai/DeepSeek-V3",
    messages: [{ role: "user", content: question }],
    temperature: 0.7
  };
  const option: http.HttpRequestOptions = {
    method: http.RequestMethod.POST,
    header: {
      'Content-Type': 'application/json',
      'Accept': 'application/json', // ✅ 加上这一行更保险
      'Authorization': `Bearer ${token}`
    },
    extraData: JSON.stringify(body),
    readTimeout: 60000,
    connectTimeout: 60000,
  }

  // ========= 请求
  const response = await httpRequest.request(url, option);
  console.log(JSON.stringify(response.result))
  let result = JSON.parse(response.result as string) as AssistantMessage
  return result.content[0].text
}
